<template>
  <div class="login-page">
    <div class="login-container">
      <!-- 登录表单 -->
      <div class="login-form">
        <h1 class="login-title">登录</h1>
        
        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <form @submit.prevent="handleLogin">
          <!-- 用户名输入 -->
          <div class="form-group">
            <label for="username">用户名</label>
            <input
              type="text"
              id="username"
              v-model="formData.username"
              placeholder="请输入用户名"
              class="form-input"
              @blur="validateUsername"
              :class="{ 'error': usernameError }"
            />
            <div v-if="usernameError" class="validation-error">
              {{ usernameError }}
            </div>
          </div>
          
          <!-- 密码输入 -->
          <div class="form-group">
            <label for="password">密码</label>
            <input
              type="password"
              id="password"
              v-model="formData.password"
              placeholder="请输入密码"
              class="form-input"
              @blur="validatePassword"
              :class="{ 'error': passwordError }"
            />
            <div v-if="passwordError" class="validation-error">
              {{ passwordError }}
            </div>
          </div>
          
          <!-- 记住我选项 -->
          <div class="form-group checkbox-group">
            <input
              type="checkbox"
              id="remember"
              v-model="formData.remember"
            />
            <label for="remember">记住我</label>
          </div>
          
          <!-- 登录按钮 -->
          <button 
            type="submit" 
            class="login-button"
            :disabled="isLoading || !isFormValid"
          >
            <span v-if="isLoading">登录中...</span>
            <span v-else>登录</span>
          </button>
        </form>
        
        <!-- 注册链接 -->
        <div class="register-link">
          <span>还没有账号？</span>
          <router-link to="/register">立即注册</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '../services/userService'

// 扩展Window接口，添加全局的用户状态更新函数
declare global {
  interface Window {
    updateUserStatus: () => void
  }
}

// 路由实例
const router = useRouter()

// 表单数据
const formData = ref({
  username: '',
  password: '',
  remember: false
})

// 表单验证状态
const usernameError = ref('')
const passwordError = ref('')
const errorMessage = ref('')

// 加载状态
const isLoading = ref(false)

// 验证用户名
const validateUsername = () => {
  const username = formData.value.username.trim()
  
  if (!username) {
    usernameError.value = '用户名不能为空'
    return false
  }
  
  if (username.length < 3 || username.length > 20) {
    usernameError.value = '用户名长度应在3-20个字符之间'
    return false
  }
  
  // 验证用户名格式（仅允许字母、数字、下划线）
  const usernameRegex = /^[a-zA-Z0-9_]+$/
  if (!usernameRegex.test(username)) {
    usernameError.value = '用户名只能包含字母、数字和下划线'
    return false
  }
  
  usernameError.value = ''
  return true
}

// 验证密码
const validatePassword = () => {
  const password = formData.value.password
  
  if (!password) {
    passwordError.value = '密码不能为空'
    return false
  }
  
  if (password.length < 6) {
    passwordError.value = '密码长度至少为6个字符'
    return false
  }
  
  passwordError.value = ''
  return true
}

// 表单是否有效
const isFormValid = computed(() => {
  return formData.value.username.trim() !== '' && 
         formData.value.password !== '' && 
         !usernameError.value && 
         !passwordError.value
})

// 处理登录
const handleLogin = async () => {
  // 重置错误消息
  errorMessage.value = ''
  
  // 验证表单
  const isUsernameValid = validateUsername()
  const isPasswordValid = validatePassword()
  
  if (!isUsernameValid || !isPasswordValid) {
    return
  }
  
  isLoading.value = true
  
  try {
    // 调用实际的登录API
    const result = await login(formData.value.username, formData.value.password)
    
    if (result.success && result.user) {
      // 登录成功后，确保用户信息也保存到localStorage
      localStorage.setItem('user', JSON.stringify(result.user))
      
      // 立即更新全局用户状态
      if (window.updateUserStatus) {
        window.updateUserStatus()
      }
      
      // 登录成功后跳转到首页
      router.push('/')
    } else {
      // 后端错误信息已通过toastService显示，此处不显示额外信息
    }
    
  } catch (error) {
    console.error('登录失败:', error)
    // 错误信息已通过toastService显示，此处不显示额外信息
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
/* 页面容器 */
.login-page {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f5f7 0%, #e5e5ea 100%);
}

/* 登录容器 */
.login-container {
  width: 100%;
  max-width: 400px;
  padding: 0 16px;
}

/* 登录表单 */
.login-form {
  background-color: white;
  padding: 40px;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 登录标题 */
.login-title {
  font-size: 2rem;
  font-weight: 700;
  color: #1C1C1E;
  text-align: center;
  margin-bottom: 32px;
  letter-spacing: -0.02em;
  line-height: 1.1;
}

/* 错误提示 */
.error-message {
  background-color: #FEF2F2;
  color: #B91C1C;
  padding: 12px 16px;
  border-radius: 12px;
  margin-bottom: 24px;
  text-align: center;
  font-size: 0.875rem;
  font-weight: 500;
}

/* 表单组 */
.form-group {
  margin-bottom: 24px;
}

.form-group label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  color: #1C1C1E;
  margin-bottom: 8px;
  letter-spacing: 0.01em;
}

/* 表单输入框 */
.form-input {
  width: 100%;
  padding: 14px 16px;
  border: 1px solid #E5E5EA;
  border-radius: 12px;
  font-size: 1rem;
  transition: all 0.2s ease;
  box-sizing: border-box;
  background-color: #F9F9F9;
  color: #1C1C1E;
}

.form-input:focus {
  outline: none;
  border-color: #007AFF;
  background-color: white;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2);
}

.form-input.error {
  border-color: #FF3B30;
  background-color: #FEF2F2;
}

.form-input::placeholder {
  color: #8E8E93;
}

/* 验证错误提示 */
.validation-error {
  color: #FF3B30;
  font-size: 0.875rem;
  margin-top: 6px;
}

/* 复选框组 */
.checkbox-group {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 32px;
}

.checkbox-group input[type="checkbox"] {
  width: 20px;
  height: 20px;
  margin: 0;
  border: 2px solid #E5E5EA;
  border-radius: 6px;
  accent-color: #007AFF;
  cursor: pointer;
  transition: all 0.2s ease;
}

.checkbox-group input[type="checkbox"]:checked {
  border-color: #007AFF;
  background-color: #007AFF;
}

.checkbox-group label {
  margin: 0;
  font-weight: normal;
  color: #6C6C70;
  cursor: pointer;
}

/* 登录按钮 */
.login-button {
  width: 100%;
  padding: 14px 24px;
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.2);
  letter-spacing: 0.01em;
}

.login-button:hover:not(:disabled) {
  background-color: #0062CC;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
}

.login-button:active:not(:disabled) {
  transform: translateY(0);
}

.login-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 注册链接 */
.register-link {
  text-align: center;
  margin-top: 24px;
  font-size: 0.875rem;
  color: #6C6C70;
}

.register-link a {
  color: #007AFF;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.2s ease;
}

.register-link a:hover {
  color: #0062CC;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-form {
    padding: 32px 20px;
    border-radius: 16px;
  }
  
  .login-title {
    font-size: 1.75rem;
  }
  
  .form-input {
    font-size: 1rem;
    padding: 12px 14px;
  }
  
  .login-button {
    font-size: 1rem;
    padding: 12px 20px;
  }
  
  .form-group {
    margin-bottom: 20px;
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 0 12px;
  }
  
  .login-form {
    padding: 24px 16px;
    border-radius: 16px;
  }
  
  .login-title {
    font-size: 1.5rem;
    margin-bottom: 24px;
  }
  
  .checkbox-group {
    margin-bottom: 24px;
  }
}

/* 高对比度模式支持 */
@media (prefers-contrast: high) {
  .login-form {
    background-color: #ffffff;
    border: 2px solid #000000;
  }
  
  .error-message {
    background-color: #ffffff;
    color: #b91c1c;
    border: 2px solid #b91c1c;
  }
  
  .form-input {
    border: 2px solid #000000;
    background-color: #ffffff;
  }
  
  .form-input.error {
    border-color: #b91c1c;
  }
  
  .form-input:focus {
    border-color: #0000ff;
  }
  
  .checkbox-group input[type="checkbox"] {
    border: 2px solid #000000;
  }
  
  .login-button {
    border: 2px solid #000000;
  }
}

/* 减少动画偏好支持 */
@media (prefers-reduced-motion: reduce) {
  .login-form {
    animation: none;
  }
  
  .form-input:focus,
  .login-button:hover:not(:disabled),
  .login-button:active:not(:disabled) {
    transform: none;
  }
}
</style>